package com.hk.admin.spring.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 默认情况下, 由Spring Security提供的BasicAuthenticationEntryPoint 返回一个完整的401 Unauthorized 的html响应页面给客户端。
 * html格式在浏览器中很好的展示了错误信息，但是对其他情形却不太适合，
 * 比如对一个 REST API 来说，json 格式会更好。
 */
public class RestAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    private static final String REALM_NAME = "hk_admin";

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,authException.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName(REALM_NAME);
        super.afterPropertiesSet();
    }

}
